<?php
/**
 * 商品管理控制器
 * @author e5
 *
 */
class GoodsController extends AuthController{
	private $db;
	public function __init(){
		parent::__init();
		$this->db = K("Goods");
	}
	/**
	 * 商品列表
	 */
	public function index() {
		//处理分页
		$total = $this->db->count();
		$page = new Page($total,7);
		$pageData = "";
		if ($total > 7){
			$pageData = $page->show();
		}
		//查询数据
		$goodsData = $this->db->field("gid,gname,gmarketprice,gshopprice,gallinventory,gclick,guptime")->limit($page->limit())->all();
		$this->assign("pageData",$pageData);
		$this->assign("goodsData",$goodsData);
		$this->display("goods");
	}
	/**
	 * 商品添加
	 */
	public function add() {
		if (IS_POST){
			if (!$this->db->addGoods()) $this->error($this->db->error);
			$this->success("添加商品成功",U("index"));
		}
		//获得分类数据
		$cate = K("Category")->field("cid,cname,pid,vshop_type_tid")->all();
		$cateData = Data::tree($cate, "cname");
		$this->assign("cateData",$cateData);
		//获得品牌数据
		$brandData = K("Brand")->field("bid,bname")->all();
		$this->assign("brandData",$brandData);
		$this->display("addGoods");
	}
	/**
	 * 商品编辑
	 */
	public function edit(){
		if (IS_POST){
			$gid = Q("post.gid",0,"intval");
			if (!$this->db->editGoods()) $this->error($this->db->error);
			//删除当前商品下的所有货品
			K("GoodsList")->where("vshop_goods_gid={$gid}")->delete();
			$this->success("编辑商品成功",U("index"));
		}
		$gid = Q("get.gid",0,"intval");
		if ($gid == 0) $this->error("商品不存在");
		//获得商品原数据
		$goodsData = M()->field("d.big,d.intro,d.service,g.*")->join("__goods__ g JOIN __detail__ d ON g.gid=d.vshop_goods_gid")->where("gid={$gid}")->find();
		$this->assign("picList",explode(",", $goodsData['big']));
		$this->assign("goodsData",$goodsData);
		//获得分类数据
		$cate = K("Category")->field("cid,cname,pid,vshop_type_tid")->all();
		$cateData = Data::tree($cate, "cname");
		$this->assign("cateData",$cateData);
		//获得品牌数据
		$brandData = K("Brand")->field("bid,bname")->all();
		$this->assign("brandData",$brandData);
		//p($this->getTypeAttrData($gid, $goodsData['vshop_type_tid']));exit();
		$this->assign("goodsAttr",$this->getTypeAttrData($gid, $goodsData['vshop_type_tid']));
		$this->display("editGoods");
	}
	/**
	 * 删除商品
	 */
	public function del(){
		$gid = Q("get.gid",0,"intval");
		if ($gid == 0) $this->error("商品不存在");
		//获得商品对应的图片数据
		$pics = M()->field("g.gpic,d.*")->join("__goods__ g JOIN __detail__ d ON g.gid=d.vshop_goods_gid")->where("g.gid={$gid}")->find();
		if (!$this->db->where("gid={$gid}")->delete()) $this->error("删除商品失败");
		//删除商品列表图
		is_file($pics['gpic']) && unlink($pics['gpic']);
		//删除商品详细信息表数据
		K("Detail")->where("vshop_goods_gid={$gid}")->delete();
		//商品属性表数据
		K("GoodsAttr")->where("vshop_goods_gid={$gid}")->delete();
		//删除货品列表表数据
		K("GoodsList")->where("vshop_goods_gid={$gid}")->delete();
		$preg = "/(<img.*?src=[\'\"])(.*?)(Upload\/.*?)([\'\"].*?\/>)/i";
		//获得商品详细图片相对地址
		preg_match_all($preg, $pics['intro'],$introPic);
		//获得售后服务图片相对地址
		preg_match_all($preg, $pics['service'],$servicePic);
		//删除商品详细图片
		foreach ($introPic[3] as $iv){
			is_file($iv) && unlink($iv);
		}
		//删除售后服务图片
		foreach ($servicePic[3] as $sv){
			is_file($sv) && unlink($sv);
		}
		//处理商品图册
		$small = explode(",", $pics['small']);
		$medium = explode(",", $pics['medium']);
		$big = explode(",", $pics['big']);
		foreach ($big as $k=>$v){
			is_file($v) && unlink($v);
			is_file($small[$k]) && unlink($small[$k]);
			is_file($medium[$k]) && unlink($medium[$k]);
		}
		$this->success("删除商品成功",U("index"));
	}
	/**
	 * 处理上传的列表图
	 */
	public function uploadList(){
		$upload = new Upload("Upload/GoodsList");
		$file = $upload->upload();
		if (empty($file)){
			$this->ajax("上传失败");
		}else {
			$data = $file[0];
			$this->ajax($data);
		}
	}
	/**
	 * 处理上传的商品图册
	 */
	public function uploadPic(){
		$upload = new Upload("Upload/GoodsPic");
		$file = $upload->upload();
		if (empty($file)){
			$this->ajax("上传失败");
		}else {
			$data = $file[0];
			//实例化图像处理类
			$image = new Image();
			//生成中图
			$medium = substr($data['path'], 0, strripos($data['path'], "."))."_medium";
			$medium .= substr($data['path'], strripos($data['path'], "."));
			$image->thumb($data['path'], $medium, 400, 400, 2);
			//生成小图
			$small = substr($data['path'], 0, strripos($data['path'], "."))."_small";
			$small .= substr($data['path'], strripos($data['path'], "."));
			$image->thumb($data['path'], $small, 68, 68, 2);
			$this->ajax($data);
		}
	}
	/**
	 * 获得类型属性(edit)
	 */
	public function getTypeAttrData($gid,$tid) {
		//获得商品属性
		$goodsAttr = M()->join("__goodsattr__ ga JOIN __typeattr__ ta ON ga.vshop_typeattr_taid=ta.taid")->where("vshop_goods_gid={$gid}")->all();
		//查询类型属性数据
		$arr = K("TypeAttr")->where("vshop_type_tid={$tid}")->all();
		$temp = array("gg"=>array(),'attrs'=>array());
		foreach ($arr as $v){
			if ($v['tatype'] == 0){
				$temp["gg"][] = $v;
			}else {
				$temp['attrs'][] = $v;
			}
		}
		//组合html标签
		$attrStr = "";
		foreach ($temp['attrs'] as $v){
			if (K("GoodsAttr")->where("vshop_typeattr_taid={$v['taid']}")->count() > 0){
				//
				foreach ($goodsAttr as $gak=>$gav){
					if ($gav['vshop_typeattr_taid'] == $v['taid']){
						$attrStr .= "<tr>";
						$attrArr = explode(",", $gav['tavalue']);
						$attrStr .= "<td>{$gav['taname']}</td><td><input type='hidden' name='taid[]' value='{$gav['taid']}' /><select name='attr[]' class='attrSelect form-control'><option value=''>请选择</option>";
						foreach ($attrArr as $aa){
							if ($aa == $gav['gavalue']){
								$attrStr .= "<option value='{$aa}' selected='selected'>{$aa}</option>";
							}else{
								$attrStr .= "<option value='{$aa}'>{$aa}</option>";
							}
						}
						$attrStr .= "</select></td><td>附加价格</td><td><input type='text' name='addprice[]' class='form-control' value='{$gav['addprice']}' /></td><td>";
						$attrStr .= "<a href='javascript:;' class='addAttr btn btn-sm btn-success'>添加属性</a></td></tr>";
					}
				}
				//
			}else {
				$attrStr .= "<tr>";
				$attrArr = explode(",", $v['tavalue']);
				$attrStr .= "<td>{$v['taname']}</td><td><input type='hidden' name='taid[]' value='{$v['taid']}' /><select name='attr[]' class='attrSelect form-control'><option value=''>请选择</option>";
				foreach ($attrArr as $aa){
					$attrStr .= "<option value='{$aa}'>{$aa}</option>";
				}
				$attrStr .= "</select></td><td>附加价格</td><td><input type='text' name='addprice[]' class='form-control' value='0' /></td><td><a href='javascript:;' class='addAttr btn btn-sm btn-success'>添加属性</a></td>";
				$attrStr .= "</tr>";
			}
		}
		$ggStr = "";
		$ggvalueArr = array();
		foreach ($goodsAttr as $gdd){
			$ggvalueArr[] = $gdd['gavalue'];
		}
		foreach ($temp['gg'] as $g){
			$ggArr = explode(",", $g['tavalue']);
			$ggStr .= "<tr><td width='150'>{$g['taname']}</td><td><input type='hidden' name='taid[]' value='{$g['taid']}' /><select name='attr[]' class='attrSelect form-control' style='width: 300px;'><option value=''>请选择</option>";
			foreach ($ggArr as $ag){
				if (in_array($ag, $ggvalueArr)){
					$ggStr .= "<option value='{$ag}' selected='selected'>{$ag}</option>";
				}else {
					$ggStr .= "<option value='{$ag}'>{$ag}</option>";
				}
			}
			$ggStr .= "</select><input type='hidden' name='addprice[]' value='0' /></td></tr>";
		}
		$newArr = array("attrStr"=>$attrStr,"ggStr"=>$ggStr);
		return $newArr;
	}
	/**
	 * 异步获得类型属性
	 */
	public function getTypeAttr() {
		if (!IS_AJAX) return 0;
		$cid = Q("post.cid",0,"intval");
		//获得类型对应的tid
		$tid = K("Category")->field("vshop_type_tid")->where("cid={$cid}")->find();
		//查询类型属性数据
		$arr = K("TypeAttr")->where("vshop_type_tid={$tid['vshop_type_tid']}")->all();
		//重组数组以便在页面插入标签
		$temp = array("gg"=>array(),'attrs'=>array());
		foreach ($arr as $v){
			if ($v['tatype'] == 0){
				$temp["gg"][] = $v;
			}else {
				$temp['attrs'][] = $v;
			}
		}
		//组合html标签
		$attrStr = "";
		foreach ($temp['attrs'] as $v){
			$attrStr .= "<tr>";
			if ($v['tavalue'] == ""){
				$attrStr .= "<td>{$v['taname']}</td><td><input type='text' name='attr[]' class='form-control' /><input type='hidden' name='taid[]' value='{$v['taid']}' /></td>";
				$attrStr .= "<td width='100'>附加价格</td><td><input type='text' name='addprice[]' class='form-control' value='0' /></td><td><a href='javascript:;' class='addAttr btn btn-sm btn-success'>添加属性</a></td>";
			}else {
				$attrArr = explode(",", $v['tavalue']);
				$attrStr .= "<td>{$v['taname']}</td><td><input type='hidden' name='taid[]' value='{$v['taid']}' /><select name='attr[]' class='attrSelect form-control'><option value=''>请选择</option>";
				foreach ($attrArr as $aa){
					$attrStr .= "<option value='{$aa}'>{$aa}</option>";
				}
				$attrStr .= "</select></td><td>附加价格</td><td><input type='text' name='addprice[]' class='form-control' value='0' /></td><td><a href='javascript:;' class='addAttr btn btn-sm btn-success'>添加属性</a></td>";
			}
			$attrStr .= "</tr>";
		}
		$ggStr = "";
		foreach ($temp['gg'] as $g){
			$ggArr = explode(",", $g['tavalue']);
			$ggStr .= "<tr><td width='150'>{$g['taname']}</td><td><input type='hidden' name='taid[]' value='{$g['taid']}' /><select name='attr[]' class='attrSelect form-control' style='width: 300px;'><option value=''>请选择</option>";
			foreach ($ggArr as $ag){
				$ggStr .= "<option value='{$ag}'>{$ag}</option>";
			}
			$ggStr .= "</select><input type='hidden' name='addprice[]' value='0' /></td></tr>";
		}
		$newArr = array("attrStr"=>$attrStr,"ggStr"=>$ggStr,'tid'=>$tid['vshop_type_tid']);
		$this->ajax($newArr);
	}
}